<template>
  <div class="modle subject" v-show="show">
    <div class="tit"><b>精选专题</b></div>
    <div class="info flex-btw">
      <span>专题样式：</span>
      <div class="switch">
        关闭 / 开启
        <el-switch v-model="switchVal" active-color="#19B098"></el-switch>
      </div>
    </div>
    <div class="box">
      <div
        :class="[{ on: styleNum == 1 }, ' css_box flex-column']"
        @click="chooseStyle('subject', 1)"
      >
        <div class="css css1">
          <span class="block"></span>
        </div>
        <div>样式一</div>
      </div>
      <div
        :class="[{ on: styleNum == 2 }, ' css_box flex-column']"
        @click="chooseStyle('subject', 2)"
      >
        <div class="css css2">
          <span class="block" v-for="i in 2" :key="i"></span>
        </div>
        <div>样式二</div>
      </div>
      <div
        :class="[{ on: styleNum == 3 }, ' css_box flex-column']"
        @click="chooseStyle('subject', 3)"
      >
        <div class="css css3">
          <span class="block"></span>
          <div class="right_b">
            <span class="block"></span>
            <span class="block"></span>
          </div>
        </div>
        <div>样式三</div>
      </div>
    </div>
    <div class="info flex-btw">
      <span>专题设置：</span>
    </div>
    <div class="content" v-if="switchVal">
      <div class="part" v-for="(item, index) in list" :key="item.id">
        <div class="flex-row-start">
          <div class="upload">
            <div
              v-if="item.img_dispaly"
              class="titimg_box"
              :style="{ width: item.img_size[0], height: item.img_size[1] }"
              @click="changeUploadType(index)"
            >
              <img class="img" :src="item.img_dispaly" fit="contain" />
              <div class="titimg_btn flex-center">更换图片</div>
            </div>
            <div
              v-else
              class="titimg_box noimg flex-center"
              :style="{ width: item.img_size[0], height: item.img_size[1] }"
            >
              <i class="el-icon-plus" style="font-size: 20px"></i>
              <span>添加图片</span>
            </div>
          </div>
          <div class="part_name">
            名称：<el-input
              class="input"
              v-model="item.name"
              placeholder="专题名称"
            ></el-input>
            <p v-if="styleNum == 3">
              注：建议尺寸{{ index==0 ? '440*440' : '440*200'}}，使用本地图片时,≤4M
            </p>
            <p v-else>
              注：建议尺寸{{
                styleNum == 1 ? "960*270" : "350*400"
              }}，使用本地图片时,≤4M
            </p>
          </div>
        </div>
        <div class="goods">
          <div class="left">添加商品：</div>
          <div class="right">
            <div class="add flex-center" @click="selectGoods(null, [index])">
              <i class="el-icon-plus"></i>
            </div>
            <div class="goods_box">
              <div
                class="good"
                v-for="(good, goodindex) in item.project_goods"
                :key="goodindex"
              >
                <div
                  class="img_box"
                  @click="selectGoods(good.goods_id, [index, goodindex])"
                >
                  <img class="img" :src="good.img" />
                  <div class="change flex-center">更换商品</div>
                </div>
                <div class="name flex-middle">{{ good.name }}</div>
                <div
                  class="remove flex-center"
                  @click="remove([index, goodindex])"
                >
                  移除
                </div>
                <div
                  class="sort flex-column"
                  :style="
                    goodindex == 0 || goodindex == item.project_goods.length - 1
                      ? 'justify-content:center;'
                      : ''
                  "
                >
                  <img
                    v-show="goodindex != 0"
                    @click="Move([index, goodindex], 'up')"
                    src="@/assets/images/shop_up.png"
                  />
                  <img
                    v-show="goodindex != item.project_goods.length - 1"
                    @click="Move([index, goodindex], 'down')"
                    src="@/assets/images/shop_down.png"
                  />
                </div>
              </div>
            </div>
            <div
              v-show="item.project_goods.length > 5"
              class="add flex-center"
              @click="selectGoods(null, [index])"
            >
              <i class="el-icon-plus"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-center">
      <div class="submit flex-center" @click="submit()">保存</div>
    </div>
  </div>
</template>

<script>
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import {
  partnerSet_projectList,
  partnerSet_editProject,
} from "@/api/shop/shop";

export default {
  name: "subject",
  props: ["show", "styleNum", "puzzleImg", "upload_img", "uploadHeader"],
  data() {
    return {
      type: 0,
      switchVal: true, //是否开启专题
      //"id":7,"name":"1","img":"1","ordid":"1",  orderid:排序
      // "project_goods":[{"goods_id":"1","ordid":"1"}
      list: [],
      list1: [
        // {img:'',name:'',project_goods:[]}
      ],
      list2: [
        // {img:'',name:'',project_goods:[]},
        // {img:'',name:'',project_goods:[]},
      ],
      list3: [
        // {img:'',name:'',project_goods:[]},
        // {img:'',name:'',project_goods:[]},
        // {img:'',name:'',project_goods:[]},
      ],
      upload_inedx: "",
    };
  },
  created() {
    let params = Object.assign(
      {
        sign: Md5(
          objKeySort(Object.assign(apiUrl().name, { type: 1 })) +
            apiUrl().appsecret
        ),
      },
      apiUrl().name
    );
    partnerSet_projectList(params).then((res) => {
      if (res.errcode == 0) {
        let type = res.data.project_arrange;
        this.type = type || 1;
        let list = res.data.list;
        this.switchVal = type == 0 ? false : true;
        this.list1 = this.setImgSize(list[1]);
        this.list2 = this.setImgSize(list[2]);
        this.list3 = this.setImgSize(list[3]);
        this.chooseStyle("subject", this.type);
      } else {
        this.$message.error(res.errmsg);
      }
    });
  },
  methods: {
    chooseStyle(name, style) {
      this.$emit("chooseStyle", name, style);
      this.type = style;
      let listtype = "list" + style;
      this.list = this.setImgSize(this[listtype]);
    },
    selectGoods(id, index) {
      let radio = id ? true : false;
      this.$emit("selectGoods", {
        id,
        index,
        ref: "refSubject",
        isRadio: radio,
      });
    },
    //获取选择的商品信息
    getSelectedGood(index, info) {
      let listtype = "list" + this.type;
      let list = this[listtype][index[0]].project_goods;
      //添加商品
      if (index.length < 2) {
        let newgoods = info.map((item) => {
          return {
            goods_id: item.id,
            name: item.name,
            img: item.pic,
          };
        });
        let allgoods = list.concat(newgoods);
        console.log("allgoods", allgoods);
        let filterGoods = [];
        for (let i = 0; i < allgoods.length; i++) {
          let flag = true;
          for (let y = i + 1; y < allgoods.length; y++) {
            if (allgoods[i].goods_id == allgoods[y].goods_id) {
              flag = false;
              break;
            }
          }
          if (flag) {
            filterGoods.push(allgoods[i]);
          }
        }

        this[listtype][index[0]].project_goods = filterGoods;

        // let goodsList = JSON.parse(JSON.stringify(list))
        // for(let i in info){
        //   goodsList.push(
        //     {goods_id:info[i].id,name:info[i].name,img:info[i].pic}
        //   )
        // }
        // this[listtype][index[0]].project_goods = goodsList
      } else {
        //更改商品
        // console.log(list[index[1]])
        let goodsList = JSON.parse(JSON.stringify(list));
        goodsList[index[1]] = {
          goods_id: info.id,
          name: info.name,
          img: info.pic,
        };
        //第二层更新监听不到，只能再次赋值第二层
        this[listtype][index[0]].project_goods = goodsList;
      }
    },
    //给每组样式的图片加宽高
    setImgSize(list) {
      if (list.length == 1) {
        list[0].img_size = ["280px", "148px"];
      } else if (list.length == 2) {
        list[0].img_size = ["126px", "148px"];
        list[1].img_size = ["126px", "148px"];
      } else if (list.length == 3) {
        list[0].img_size = ["106px", "148px"];
        list[1].img_size = ["166px", "68px"];
        list[2].img_size = ["166px", "68px"];
      }
      return list;
    },
    uploadSuccess(res, index) {
      if (res.code == 0) {
        this.list[index].img_dispaly = res.data.src;
        this.list[index].img = res.data.path;
        this.$forceUpdate(); //强制视图更新
      } else {
        this.$message.error(res.errmsg);
      }
    },
    uploadErr() {
      this.$message.error("上传失败，请重试");
    },
    remove(index) {
      this.$confirm("是否移除该商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let goods = this.list[index[0]].project_goods;
          goods.splice(index[1], 1);
        })
        .catch(() => {});
    },
    //移动排序
    Move(index, type) {
      let aindex = index[0],
        bindex = index[1];
      let toIndex;
      type == "up" ? (toIndex = bindex - 1) : (toIndex = bindex + 1);
      let arr_temp = [].concat(this.list[aindex].project_goods); //创建一个新的临时数组，用以操作后不变更原数组
      arr_temp.splice(toIndex, 0, arr_temp.splice(bindex, 1)[0]); //在toIndex位置插入从index位置截取的元素
      this.list[aindex].project_goods = arr_temp;
    },
    submit() {
      let data = { project_arrange: this.switchVal ? this.type : 0 };
      let tips = {
        name: false,
        img: false,
        project_goods: false,
      };
      if (this.switchVal) {
        let dataList = JSON.parse(JSON.stringify(this.list));

        let list = dataList.map((item, index) => {
          // "id":7,"name":"1","img":"1","ordid":"1",
          // "project_goods":[{"goods_id":"1","ordid":"1"}
          !item.name ? (tips.name = true) : "";
          !item.img ? (tips.img = true) : "";
          !item.name ? (tips.name = true) : "";
          item.project_goods.length == 0 ? (tips.project_goods = true) : "";
          return {
            id: item.id,
            name: item.name,
            img: item.img,
            ordid: index + 1,
            project_goods: item.project_goods.map((good, goodindex) => {
              return {
                goods_id: good.goods_id,
                ordid: goodindex + 1,
              };
            }),
          };
        });
        list = JSON.stringify(list);
        Object.assign(data, { list });
      }
      if (tips.name) {
        this.$message.warning("请输入专题名称");
        return;
      }
      if (tips.img) {
        this.$message.warning("请上传图片");
        return;
      }
      if (tips.project_goods) {
        this.$message.warning("请选择展示的商品");
        return;
      }
      let params = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      partnerSet_editProject(params).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("保存成功");
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 打开父组件的图片上传方式
    changeUploadType(index) {
      this.upload_inedx = "";
      if (index !== "") {
        this.upload_inedx = index;
      }
      this.$emit("changeUploadType", {
        pid: 2,
        ref: "refSubject",
      });
    },
    // 获取父级返回的图片信息
    getUploadImg(res) {
      let index = this.upload_inedx;
      this.uploadSuccess(res, index);
    },
  },
};
</script>

<style lang="scss" scoped>
.subject {
  .info {
    margin-bottom: 30px;
  }
  .box {
    margin-bottom: 30px;
    .css_box {
      width: 248px;
      height: 158px;
      border: 1px solid #d1d1d1;
      background: #fff;
      justify-content: center;
      align-items: center;
      &.on {
        border-color: #19b098;
      }
      + .css_box {
        margin-left: 20px;
      }
      .css {
        width: 100%;
        height: 110px;
        padding: 0 20px;
        .block {
          background: #03a98e;
        }
      }
      .css1 {
        display: flex;
        align-items: center;
        justify-content: space-around;
        .block {
          width: 140px;
          height: 74px;
        }
      }
      .css2 {
        padding: 0 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        .block {
          width: 63px;
          height: 74px;
          + .block {
            margin-left: 7px;
          }
        }
      }
      .css3 {
        display: flex;
        align-items: center;
        justify-content: center;
        .block {
          margin-right: 7px;
          width: 53px;
          height: 75px;
        }
        .right_b {
          display: flex;
          flex-direction: column;
          .block {
            width: 83px;
            height: 34px;
            + .block {
              margin-top: 7px;
            }
          }
        }
      }
    }
  }
  .content {
    .part {
      padding: 20px;
      background: #fff;
      margin-bottom: 14px;
      .titimg_box {
        position: relative;
        .titimg_btn {
          position: absolute;
          top: 0;
          width: 100%;
          height: 20px;
          background: #19b098;
          color: #fff;
          font-size: 10px;
          cursor: pointer;
        }
        .img {
          width: 100%;
          height: 100%;
        }
        &.noimg {
          border: 2px dashed #d3d3d3;
        }
      }
      .part_name {
        margin-left: 15px;
        .input {
          width: 230px;
          font-size: 14px;
          color: #333333;
          font-family: Microsoft YaHei;
        }
        p {
          margin-top: 10px;
          font-size: 13px;
          color: #666666;
          font-family: Microsoft YaHei;
        }
      }
      .goods {
        display: flex;
        background: #fff;
        min-width: 500px;
        padding: 30px 0px;
        .left {
          color: #616161;
          font-size: 14px;
          margin-right: 10px;
        }
        .right {
          .goods_box {
            margin: 24px 0;
            .good {
              display: flex;
              .img_box {
                position: relative;
                box-sizing: border-box;
                width: 60px;
                height: 60px;
                .img {
                  border: 1px solid #19b098;
                  width: 60px;
                  height: 60px;
                }
                .change {
                  width: 100%;
                  position: absolute;
                  bottom: 0;
                  left: 0;
                  right: 0;
                  color: #fff;
                  background: #19b098;
                  font-size: 10px;
                  padding: 1px 0;
                }
              }
              .name {
                width: 154px;
                height: 60px;
                background: #e1f3f0;
                border-top: 1px solid #19b098;
                border-bottom: 1px solid #19b098;
                padding-left: 20px;
                color: #404040;
                font-size: 14px;
              }
              .remove {
                width: 26px;
                height: 60px;
                background: #d81e1e;
                color: #fff;
                writing-mode: vertical-lr;
              }
              .sort {
                justify-content: space-between;
                margin-left: 20px;
              }
              & + .good {
                margin-top: 20px;
              }
            }
          }
          .add {
            width: 60px;
            height: 60px;
            border: 2px solid #d3d3d3;
            color: #d3d3d3;
            font-size: 20px;
          }
        }
      }
    }
  }
}
.submit {
  cursor: pointer;
}
</style>